package com.orhon.smartcampus.modules.material.mutation;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.orhon.smartcampus.auth.JwtUtils;
import com.orhon.smartcampus.basicComponents.Result;
import com.orhon.smartcampus.modules.base.dao.SchoolsDao;
import com.orhon.smartcampus.modules.base.entity.Schools;
import com.orhon.smartcampus.modules.material.dao.FloorDao;
import com.orhon.smartcampus.modules.material.dao.UnitDao;
import com.orhon.smartcampus.modules.material.entity.Floor;
import com.orhon.smartcampus.modules.material.entity.Unit;
import com.orhon.smartcampus.modules.material.gqlInputModel.GQLFloorInput;
import com.orhon.smartcampus.modules.material.inputMapper.FloorInputMapper;
import com.orhon.smartcampus.modules.user.dao.TokenService;

import graphql.schema.DataFetcher;
import graphql.schema.DataFetchingEnvironment;

@Component
public class AddFloorMutation implements DataFetcher {


    @Autowired
    FloorDao floorDao;

    @Autowired
    UnitDao unitDao;

    @Autowired
    SchoolsDao schoolsDao;

    @Autowired
    TokenService tokenService;

    /**
     * 楼层管理
     * editor : ths
     */
    @Override
    public Object get(DataFetchingEnvironment environment) throws Exception {

        //String token = (String) SecurityUtils.getSubject().getPrincipal();
        String token = tokenService.getSystemToken();
        Long schoolId = JwtUtils.getSchoolId(token);

        GQLFloorInput input = FloorInputMapper.MAPPER.mapInput(environment.getArgument("inputData"));

        Floor floor = null;

        if (input.getId() != null) {
            floor = floorDao.get(Floor.class, input.getId());
            floor.setUpdatedAt(new Date());
        } else {
            floor = new Floor();
            floor.setCreatedAt(new Date());
        }

        if (input.getUnit_id() != null) {
            floor.setMaterialUnitByUnitId(unitDao.get(Unit.class, input.getUnit_id()));
        }
        if (schoolId != null) {
            floor.setBaseSchoolsBySchoolId(schoolsDao.get(Schools.class, schoolId));
        }
        if(input.getCode() != null){

            floor.setFloorCode(input.getCode());
        }
        if(input.getTel() != null){

            floor.setFloorTel(input.getTel());
        }
        if(input.getManager() != null){

            floor.setFloorManager(JSON.toJSONString(input.getManager()));
        }
        if(input.getName() != null){

            floor.setFloorName(JSON.toJSONString(input.getName()));
        }
        try {
            floorDao.saveOrUpdate(floor);
        } catch (Exception e) {
            return Result.error(500, "" + e);
        }
        return Result.ok();
    }
}

